//
//  AnalysisAdvise.swift
//  Speek
//
//  Created by MikeHo on 2023/6/29.
//

import SwiftUI
import Alamofire
import CoreData
import Combine

struct AnalysisData{
    var totalIncome: Double
    var totalExpense: Double
    var maxAmountBill: BillDetail
    var maxChangedBill: MaxChangedBill
}

struct AnalysisAdvise: View {
    @Environment(\.dismiss) private var dismiss
    @Binding var analysisData: AnalysisData
    @Binding var outputText: String
    @Binding var isLoading: Bool
    
    @State private var isSuccess = false
    @State private var isFail = false

    var body: some View {
        NavigationStack {
            VStack{
                if isLoading {
                    LoadingView
                } else if isSuccess {
                    ScrollView {
                        VStack(spacing: 10) {
                            AdviceText(outputText: $outputText)
                        }
                    }
                    .padding(.horizontal, 10)
                    .preferredColorScheme(.dark)
                } else if isFail {
                    FailedView
                }
            }
            .padding(.horizontal,10)
            .preferredColorScheme(.dark)
            .navigationTitle("消费建议")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar{
                ToolbarItem(placement: .navigationBarTrailing){
                    Button("完成", action: {
                        dismiss()
                    })
                }
            }
        }
        .onAppear {
            
            analyzeByGPT(inputData: analysisData) { result in
                if result != "" {
                    isSuccess = true
                } else {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        isFail = true
                    }
                }
                outputText = result
                isLoading = false
            }
        }
    }
}

extension AnalysisAdvise{
    var LoadingView : some View{
        
        VStack{
            ProgressView("分析中...")
                .font(.title)
                .progressViewStyle(CircularProgressViewStyle(tint: .orange))
                .foregroundColor(.orange)
                .cornerRadius(10)
        }
        .ignoresSafeArea(.all)
        
    }
}
extension AnalysisAdvise{
    var FailedView : some View{
        
        VStack{
            ProgressView{
                
                Text("暂无法生成建议")
                Text("请检查网络连接以及消费信息是否完整")
            }
                .font(.headline)
                .progressViewStyle(CircularProgressViewStyle(tint: .orange))
                .foregroundColor(.orange)
                .cornerRadius(10)
        }
        .ignoresSafeArea(.all)
        
    }
}

struct AdviceText: View {
    @Binding var outputText: String
    
    var body: some View {
        
        
        VStack{
            Text(outputText)
                .font(.body)
        }
        .padding(.top,30)
    }
    
}

//将打包好的消费数据从数据结构AnalysisData处理为字符串String，并发送获取输出
func analyzeByGPT(inputData:AnalysisData, completion: @escaping (String)-> Void){
    
    //运行是否完成Bool
    var result:Bool = false
    var outputText:String = ""
    let apiKeyHeader = "Authorization"
    let apiKeyValue = "Bearer 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"
    let url = URL(string: "https://api.openai.com/v1/chat/completions")!
        
    var inputText:String = ""
    
    let inputText1 = "总体内容： 总收入：" + String(inputData.totalIncome) + " 总支出：" + String(inputData.totalExpense)
    
    let inputText2 = " 本月最大一笔支出内容： 事件：" + String(inputData.maxAmountBill.name ?? "") +  " 类型："
    + String(inputData.maxAmountBill.type ?? "") + " 金额：" + String(inputData.maxAmountBill.cost)
    
    let inputText3 = " 与上个月相比支出的最大变化： 变化金额：" + String(inputData.maxChangedBill.changedAmount) + " 变化率：" + String(inputData.maxChangedBill.changedRatio)
    
    inputText = inputText1 + inputText2 + inputText3
    
    print(inputText)
    
    
    let str = "请分析如下语句，给出对用户收入和支出情况的分析建议：/n"
    // 替换为您的预定义字符串
    let content = "\(str) \(inputText)"
    
    let message = [
        ["role": "system", "content": "You are a helpful assistant."],
        ["role": "user", "content": content]
    ]
    let parameters = ["model": "gpt-3.5-turbo", "messages": message] as [String: Any]
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue(apiKeyValue, forHTTPHeaderField: apiKeyHeader)
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
    
    URLSession.shared.dataTask(with: request) { data, response, error in
        if let data = data {
            if let decodedResponse = try? JSONDecoder().decode(ChatResponse.self, from: data) {
                DispatchQueue.main.async {
                    outputText = decodedResponse.choices[0].message.content
                    print(outputText)
                    completion(outputText) //闭包获取执行成功状态
                }
            }
        }
        completion("") //闭包获取执行失败状态
    }.resume()
}
